package com.qf.common.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class CopyNotNullUtils {
    /**
     * 复制非空属性值
     *
     * @param source
     * @param target
     */
    public static void copyNonNullProperties(Object source, Object target) {
        try {
            // 获取源对象的所有属性名称
            for (String propertyName : BeanUtils.describe(source).keySet()) {
                // 获取源对象中对应属性的值
                Object value = PropertyUtils.getProperty(source, propertyName);
                // 检测目标对象的对应属性是否为null、空字符串或为0.0
                Object targetValue = PropertyUtils.getProperty(target, propertyName);
                if (value != null) {
                    if (targetValue == null || "".equals(targetValue) || targetValue instanceof Number && ((Number) targetValue).doubleValue() == 0.0) {
                        PropertyUtils.setProperty(target, propertyName, value);
                    }
                }
            }
        } catch (Exception e) {
            // 打印详细的异常信息
            e.printStackTrace();
            System.err.println("复制属性失败： " + e.getMessage());
        }
    }
}
